import axios from 'axios'
import { Message } from 'element-ui';
import { getTimeStamp, getToken } from './auth';
import store from '@/store';
import router from '@/router';


const instance = axios.create({
  baseURL: '/api'
})
const time = 30*60*1000
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  const token = getToken()
  if(token) {
    // 设置超时判断
    const currentTime = Date.now()
    // console.log(Date.now());
    const timeStamp = getTimeStamp()
    const space = currentTime - timeStamp
    if( space>time ){
      Message.warning('登陆超时，请重新登录')
      store.dispatch('user/logout')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
      return Promise.reject(new Error('登陆超时'))
    }

    config.headers.Authorization = `Bearer ${token}`
  }
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  let {data: {success,message}} = response
  if(success){
    // console.log(response.data);
    return response.data;
  }else{
    Message.error(message)
    // console.log(message);
    return Promise.reject(new Error(message))
  }
}, function (error) {
  // 对响应错误做点什么
  console.dir(error);
  if(error.response && error.response.data && error.response.data.code === 10002){
    store.dispatch('user/logout')
    Message.warning('登陆超时,请重新登录')
    // console.log(window.location.href.split('#')[1]);
    router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
  }
  return Promise.reject(error);
});

export default instance